<%--
  Created by IntelliJ IDEA.
  User: 陈fairy
  Date: 2018-12-30
  Time: 9:44
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户角色</title>
    <jsp:include page="${pageContext.request.contextPath}/common/common.jsp"/>
    <!--启用较验-->
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/bootstrapvalidator/bootstrapValidator.min.css">
    <script src="${pageContext.request.contextPath}/static/bootstrapvalidator/bootstrapValidator.min.js"></script>
    <script src="${pageContext.request.contextPath}/static/bootstrapvalidator/zh_CN.js"></script>
    <!--sweet提示框-->
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/hplus/css/plugins/sweetalert/sweetalert.css" />
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/hplus/js/plugins/sweetalert/sweetalert.min.js"></script>
    <!--百度地图-->
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=x4GWag386iWUaZ6PVMEOSqLrkUWr4OE8"></script>
    <link href="${pageContext.request.contextPath}/static/treeview/bootstrap-treeview.min.css" rel="stylesheet">
    <script src="${pageContext.request.contextPath}/static/treeview/bootstrap-treeview.min.js"></script>
    <script>
        $(function () {
            $("#role").bootstrapTable({
                url:'${pageContext.request.contextPath}/Role/queryRole',
                toolbar:'#dtn',//工具按钮用哪个容器
                striped: true,//隔行换色
                showRefresh: true,//是否显示刷新按钮
                height: 500,//行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
                uniqueId: "id",//每一行的唯一标识，一般为主键列
                showToggle:true,//是否显示详细视图和列表视图的切换按钮
                //detailView:true,//是否显示父子表
                pagination:true, //是否显示分页（*）
                pageSize : 4,//单页记录数
                pageList : [ 5, 10, 20, 30 ],//可选择单页记录数
                /* sidePagination:"server",//分页方式：client客户端分页，server服务端分页（*）
                 queryParams: function (params) {
                 var temp = {
                     limit : params.limit,
                     offset : params.offset
                 }
                 return temp;
                 },*/
                columns:[
                    {checkbox: true},
                    {field: 'id', title: '编号'},
                    {field: 'rname', title: '职位'},
                    {
                        title:'操作',
                        formatter:function(value,row,index){
                            return "<button class='btn  btn-info' data-toggle=\"modal\" data-target=\"#updateModel\" onclick='upRole("+row.id+")'>修改</button>";
                        }
                    },
                ]
            })
        })
        //校验
        $(function () {
            <!--校验框架-->
            $('#addmodal').bootstrapValidator({
                message: 'This value is not valid',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    name: {
                        message: 'The username is not valid',
                        validators: {
                            notEmpty: {
                                message: '用户名不能为空！'
                            }
                        }
                    }
                }
            });
        });

        function toadd() {
            $("#addmodal").modal("show") ;
        }
        //增加用户
        function doAdd(){

            //启用较验
            // $('#addmodal').data('bootstrapValidator').validate();
            $('#addmodal').data('bootstrapValidator').validate();
            //验证是否通过true/false
            var flag = $('#addmodal').data('bootstrapValidator').isValid() ;
            if (flag){
                //
                //绑定当前页开始
                var options = $("#role").bootstrapTable('getOptions') ;
                //得到当前页
                var pn = options.pageNumber ;
                $("input[name='pn']").val(pn) ;
                //序列化表单
                var formStr=$('#userform').serialize();
                //处理表单控件的中文乱码
                AddRole = decodeURIComponent(formStr,true);
                alert(AddRole)
                $.ajax({
                    'type':'post',
                    'url':'/Role/addsx',
                    'data':AddRole,
                    success:function(data){
                        //关闭对话框
                        $("#addmodal").modal('hide') ;
                        //重新加载表格
                        $('#role').bootstrapTable('load',data) ;
                        //提示增加成功
                        swal("提示信息", "增加成功!", "success");
                    }
                })
            }


        }
        //删除
        function delRoom(id) {
            var ids = "" ;
            //1.得到要删除的行
            //返回所选的行，当没有选择任何行的时候返回一个空数组。
            var rows = $("#role").bootstrapTable("getSelections") ;
            if (rows.length==0){
                alert("请选择要删除的数据！") ;
            }
            else{
                $.each(rows,function (index,row) {
                    ids = ids + row.id + "-";

                }) ;
                swal({
                    title: "您确定要删除这条信息吗",
                    text: "删除后将无法恢复，请谨慎操作！",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "删除",
                    closeOnConfirm: false
                }, function () {
                    //得到当前页
                    //绑定当前页开始
                    //var options = $("#roominfotb").bootstrapTable('getOptions') ;
                    //得到当前页
                    //var pn = options.pageNumber ;
                    $.post("/Role/deleteRole",{'ids': ids},function(data){
                        //友好的提示
                        swal({title:"删除成功！",
                                text:"您已经永久删除了这条数据。",
                                type:"success"},
                            //刷新页面
                            function(){window.location=""});

                    })

                });
            }
        }
    </script>
</head>
<body>
<div class="container">
<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title">用户角色</h3>
    </div>
    <div class="panel-body">
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group col-sm-3">
                    <button onclick="toadd()" class="btn btn-primary"><span class="glyphicon glyphicon-plus"></span>&nbsp;&nbsp;增加</button>
                </div>
                <div class="form-group col-sm-3">
                    <button onclick="delRoom()" class="btn btn-primary"><span class="glyphicon glyphicon-trash"></span>&nbsp;&nbsp;删除</button>
                </div>
                <%--<button onclick="doDel()" class="btn btn-primary"><span class="glyphicon glyphicon-trash" ></span>&nbsp;&nbsp;删除</button>--%>
            </div>
            <div class="col-sm-6">
                <form  class="form-inline pull-right">
                    <input id="username" type="text" class="form-control">
                    <button class="btn btn-primary" onclick="searcha()" type="button"><span class="glyphicon glyphicon-search"></span>&nbsp;&nbsp;搜索</button>
                </form>
            </div>
        </div>
        <table id="role"></table>
    </div>
</div>
</div>

<%--添加模态框--%>
<div class="modal inmodal" id="addmodal">
    <div class="modal-dialog">
        <form class="form-horizontal" id="userform" method="post" role="form">
            <input type="hidden" name="pn">
            <div class="modal-content animated bounceInLeft">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" >
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title">角色增加</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label class="col-sm-4 text-right">角色名称：</label>
                        <div class="col-sm-6">
                            <input type="text" class="form-control" name="rname" placeholder="角色"/>
                        </div>
                    </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="doAdd()">添加</button>
                </div>
            </div>
            </div>
        </form>
    </div>
</div>


<!--分配权限的模态框-->
<div class="modal fade" id="modal-id">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">提示信息</h4>
            </div>
            <div class="modal-body">
                <div id="searchTree"></div>
                <input type="hidden" id="roleId">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button onclick="fenpei()" type="button" class="btn btn-primary">分配</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->


</body>
</html>

<script>
    var nodeCheckedSilent = false;

    function nodeChecked(event, node) {
        if (nodeCheckedSilent) {
            return;
        }
        nodeCheckedSilent = true;
        checkAllParent(node);
        checkAllSon(node);
        nodeCheckedSilent = false;
    }
    var nodeUncheckedSilent = false;

    function nodeUnchecked(event, node) {
        if (nodeUncheckedSilent)
            return;
        nodeUncheckedSilent = true;
        uncheckAllParent(node);
        uncheckAllSon(node);
        nodeUncheckedSilent = false;
    }

    //级联选中所有子节点
    function checkAllSon(node) {
        $('#searchTree').treeview('checkNode', node.nodeId, {
            silent: true
        });
        if (node.nodes != null && node.nodes.length > 0) {
            for (var i in node.nodes) {
                checkAllSon(node.nodes[i]);
            }
        }
    }
    //级联取消所有子节点
    function uncheckAllSon(node) {
        $('#searchTree').treeview('uncheckNode', node.nodeId, {
            silent: true
        });
        if (node.nodes != null && node.nodes.length > 0) {
            for (var i in node.nodes) {
                uncheckAllSon(node.nodes[i]);
            }
        }
    }

    function upRole(id){
        console.log(id);
        $("#modal-id").modal("show");
        $("#roleId").val(id);
        $.post('${pageContext.request.contextPath}/Role/fenpei',{'oid':id},function(data){
            $("#searchTree").treeview({
                showCheckbox: true,
                data: data,
                onNodeChecked: nodeChecked,
                onNodeUnchecked: nodeUnchecked
            }) ;
        }) ;
    }

    function fenpei() {
        var roleid = $("#roleId").val();
        console.log(roleid);
        var pmid = "" ;
        //1.
        var cks = $("#searchTree").treeview('getChecked') ;
        $.each(cks,function (i,n) {
            //2.
            pmid += n.id+"-" ;
        })
        console.log(pmid);
        $.post('/Role/grantPermission',{'roleid':roleid,'pmid':pmid},function (data) {
            console.log(data.msg);
            if (data.msg=="1" ){
                //关闭对话框
                $("#modal-id").modal('hide') ;
            }

        })
    }
    //选中全部父节点
    function checkAllParent(node) {
        $('#searchTree').treeview('checkNode', node.nodeId, {
            silent: true
        });
        var parentNode = $('#searchTree').treeview('getParent', node.nodeId);
        if (!("nodeId" in parentNode)) {
            return;
        } else {
            checkAllParent(parentNode);
        }
    }
    //取消全部父节点
    function uncheckAllParent(node) {
        $('#searchTree').treeview('uncheckNode', node.nodeId, {
            silent: true
        });
        var siblings = $('#searchTree').treeview('getSiblings', node.nodeId);
        var parentNode = $('#searchTree').treeview('getParent', node.nodeId);
        if (!("nodeId" in parentNode)) {
            return;
        }
        var isAllUnchecked = true; //是否全部没选中
        for (var i in siblings) {
            if (siblings[i].state.checked) {
                isAllUnchecked = false;
                break;
            }
        }
        if (isAllUnchecked) {
            uncheckAllParent(parentNode);
        }

    }

    //级联选中所有子节点
    function checkAllSon(node) {
        $('#searchTree').treeview('checkNode', node.nodeId, {
            silent: true
        });
        if (node.nodes != null && node.nodes.length > 0) {
            for (var i in node.nodes) {
                checkAllSon(node.nodes[i]);
            }
        }
    }
    //级联取消所有子节点
    function uncheckAllSon(node) {
        $('#searchTree').treeview('uncheckNode', node.nodeId, {
            silent: true
        });
        if (node.nodes != null && node.nodes.length > 0) {
            for (var i in node.nodes) {
                uncheckAllSon(node.nodes[i]);
            }
        }
    }
</script>
